<?php
/**
 * 应用配置服务类
 * @author sixihaoyue <sixihaoyue@qq.com>
 */
class ConfigModel extends BpfModel
{
  private static $_values = [];
  private static $_set = [];

  /**
   * 获取配置值
   * @param string $name 配置名
   * @param mixed $default 默认值
   * @return mixed
   */
  public function get($name = null, $default = null)
  {
    if (isset(self::$_values[$name])) { return self::$_values[$name]; }
    $mysqlModel = $this->getModel('mysql');
    if (isset($name)) {
      $return = $mysqlModel->getSqlBuilder()
        ->from('configs')
        ->where('name', $name)->query()->row();
      self::$_values[$name] = isset($return->value) ? json_decode($return->value) : null;
      return self::$_values[$name] ?? $default;
    } else {
      return self::$_values;
    }
  }

  /**
   * 设置配置
   * @param string $name 配置名
   * @param mixed $value 配置值
   */
  public function set($name, $value)
  {
    self::$_values[$name] = $value;
    self::$_set[$name] = json_encode($value);
  }

  /**
   * 保存配置
   * @return bool
   */
  public function save()
  {
    $mysqlModel = $this->getModel('mysql');
    if (empty(self::$_set)) {
      return false;
    }
    $set = [];
    $updated = REQUEST_TIME;
    foreach (self::$_set as $key => $value) {
      $set[] = '("' . $key . '","' . $mysqlModel->escape($value) . '","' . $updated . '")';
    }
    self::$_set = [];
    self::$_values = [];
    try {
      $sql = 'REPLACE INTO `configs` (`name`, `value`, `updated`) VALUES ' . implode(',',$set);
      return $mysqlModel->query($sql)->affectedRows();
    } catch (BpfException $e) {
      return false;
    }
  }

  public function incr($key, $incr = 1)
  {
    $mysqlModel = $this->getModel('mysql');
    $incr = $mysqlModel->escape($incr);
    self::$_values[$key] = null;
    $sql = 'INSERT INTO `configs` (`name`, `value`, `updated`) VALUES ("'
      . $key . '","' . $incr . '","' . REQUEST_TIME .
    '") ON DUPLICATE KEY UPDATE `updated` = `updated`, `value`=`value`+ ' . $incr;
    return $mysqlModel->query($sql)->affectedRows();
  }
}
